<?php
/**
 * 
 * $user_oid, $community_oid - два значения однозначно идентифицирующие члена.
 * 
 * @package default
 * @author Alexander Sibiryakov
 **/
class Model_Member extends RL_Model2 {
	
	/*
	 * @return fobject
	 */ 
	public function createMember($user_oid, $community_oid) {
		return $this->store->create( "fmember", array(
			"user_oid"=>$user_oid,
			"community_oid"=>$community_oid
		));
	}
	
	public function saveMember(fobject $obj) {
		return ($obj->save() && $obj->inSense('member'));
	}
	
	/*
	 * @return boolean
	 */ 	
	public function removeMember($user_oid, $community_oid) {
		// два DELETE из store_objects, store_member
		$prefix = $this->db->db_prefix;
		
		$sql = "SELECT oid FROM {$prefix}class_member WHERE community_oid=".$community_oid." AND user_oid=".$user_oid;
		$_a = $this->db->queryOne($sql);
		$oid = $_a['oid'];
		
		$sql = "DELETE FROM {$prefix}class_member WHERE oid=".$oid;
		$this->db->execute($sql);
		
		$sql = "DELETE FROM {$prefix}objects WHERE oid=".$oid;
		return $this->db->execute($sql);
	}
	
	/*
	 * @return fobject or false
	 */ 
	public function getMember($user_oid, $community_oid) {
		$ql = "select objects where member.community_oid==:0 and member.user_oid==:1";
		$object = $this->store->find( $ql, array($community_oid, $user_oid) )->next();
		
		if ($object instanceof fobject) {
			return $object;
		} else return false;
	}
	/*
	 * @param $date дата в формате ГГГГ-ММ-ДД ЧЧ:ММ:СС
	 */ 
	public function setJoinDate(fobject $member, $date=NULL) {
		if (!$date) {
			$member->data['join_date'] = RL_CyrDate::newNow()->format("%Y-%m-%d %H:%i:%s");
		} else {
			$member->data['join_date'] = RL_CyrDate::newFromStr("%Y-%m-%d %H:%i:%s", $date);
		}
	}
}
